package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.github.sd4324530.fastweixin.handle.EventHandle;
import com.github.sd4324530.fastweixin.handle.MessageHandle;
import com.github.sd4324530.fastweixin.servlet.WeixinSupport;
import com.github.sd4324530.fastweixin.util.SignUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.web.utils.ResponseUtils;
import org.dromara.system.domain.bo.SysAccountBo;
import org.dromara.system.domain.vo.SysAccountVo;
import org.dromara.system.service.ISysAccountService;
import org.dromara.wx.AdminWeixinSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 公众号验证服务
 *
 * @author fly
 */
@SaIgnore
@Slf4j
@Controller
@RequestMapping("/app/wx/mp/api")
public class WxMpApiController extends BaseController {

    @Autowired
    ISysAccountService accountService;

    /**
     * 公众号验证服务
     *
     * @return 结果
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    public void api(@PathVariable Long id, @RequestParam(required = false) String signature,
                    @RequestParam(required = false) String timestamp, @RequestParam(required = false) String nonce,
                    HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {

        if (id != null
            && StringUtils.isNotEmpty(signature)
            && StringUtils.isNotEmpty(timestamp)
            && StringUtils.isNotEmpty(nonce)) {
            log.error("id:{},signature:{},timestamp:{},nonce:{}", id, signature, timestamp, nonce);

            SysAccountVo account = accountService.queryById(id);
            if (account != null) {
                boolean check = SignUtil.checkSignature(account.getToken(), signature, timestamp, nonce);
                if (check) {
                    if (request.getMethod().equals(RequestMethod.GET.name())) {
                        String echostr = ServletRequestUtils.getRequiredStringParameter(request, "echostr");

                        ResponseUtils.renderText(response, echostr);
                    } else {
                        try {
                            Map<String, MessageHandle> messageHandleMapp = SpringUtils.
                                getBeansOfType(MessageHandle.class);
                            Map<String, EventHandle> eventHandleMapp = SpringUtils.
                                getBeansOfType(EventHandle.class);
                            AdminWeixinSupport support = new AdminWeixinSupport(account,
                                messageHandleMapp.values(),
                                eventHandleMapp.values());
                            //设置响应编码格式
                            response.setCharacterEncoding("UTF-8");
                            String resp = support.processRequest(request);
                            log.error("响应:" + resp);
                            PrintWriter pw = response.getWriter();
                            pw.write(resp);
                            pw.flush();
                            pw.close();
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }

}
